﻿using System;
using System.Globalization;
using System.Web;
using System.IO;
using System.Collections.Generic;
using System.Net.Mail;
using SpiderMaster.AspNet.TradingSystem.BusinessLogicLayer;

namespace SpiderMaster.AspNet.TradingSystem
{
    public class Global : HttpApplication
    {
        [ReganSchroder(19, 10, 5, 10, 2009)]
        private void Application_Start(Object sender, EventArgs e)
        {
            TradingCenterHttpApplication.OnStart();

            try { RoleManagement.Initialize().Start(); }
            catch { }

            //TODO: 2012 ListingManager.Start();

            Application["UsersOnlineTotal"] = 0;
        }

        private void Session_Start(Object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            Session["start"] = DateTime.Now;
            Application.Lock();

            Application["UsersOnlineTotal"] = Convert.ToInt32(Application["UsersOnlineTotal"], CultureInfo.CurrentCulture) + 1;

            Application.UnLock();
        }

        private void Application_BeginRequest(Object source, EventArgs e)
        {
            TradingCenterHttpApplication.OnBeginRequest(source);
        }

        /// <summary>
        /// Handles the AuthenticateRequest event of the Application control.	
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        /// <remarks></remarks>
        // because url rewriting is combined with forms authentication, the rewriting must take place in Application_AuthorizeRequest, so that User.Identity is available
        [ReganSchroder(21, 5, 2010)]
        protected void Application_AuthorizeRequest(object sender, EventArgs e)
        {
            /////////////////////////////////////////////////////////////////////
            // It is not recommended that you modify this code how ever if you //
            // Seriously think its worth while make a copy of this file first. //
            /////////////////////////////////////////////////////////////////////
            string currentURL = SystemManager.Current.GetSiteUrl().Add(Request.RawUrl);

            if (currentURL.ToLower().Contains("www.SpiderMaster.org".Add(DemoPath).ToLower()))
                Redirect();
            // else if (currentURL.ToLower().Contains(DemoPath.ToLower()))
            // Context.RewritePath(Request.FilePath.ToLower().Replace(DemoPath.ToLower(), "/").Replace("Defalut.aspx", ""), true);

        }
        private const string DemoPath = "/TC/2010/Demo/";
        private void Redirect()
        {
            new Redirect("http://TradingCenter.SpiderMaster.org" + Request.RawUrl.Replace(DemoPath.ToLower(), "/"));
            Response.End();
        }

        [ReganSchroder(27, 10, 1, 10, 2009)]
        private void Application_Error(Object sender, EventArgs e)
        {
            // Retrieve last error and log it, redirecting to Error.aspx (avoiding infinite loops)

            Exception ex = Server.GetLastError();

            // TODO: local LogError(ex);
            string url = "";
            try { url = HttpContext.Current.Request.Url.ToString(); }
            catch { }
            try
            {
                List<string> recipients = RoleManagement.GetRecipients(true, false, PredefinedRole.GeneralAdministrator);

                if (recipients.Count > 0)
                {
                    EmailManager.AsyncSendMassEmail(recipients, SiteSettings.Current.MailSenderAddressFormatted, "Error Notification", "An error occurred on " +
                           DateTime.Now.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss") + " (server time) in the " + Version.Current.Name + " hosted at " +
                           SystemManager.Current.GetSiteUrl() + " - server stack trace follows.\r\n\r\n" +
                           (!string.IsNullOrEmpty(url) ? url + "\r\n\r\n" : "") +
                           ex.ToString(), false, new SmtpClient());
                }
            }
            catch { }

            Session["LastError"] = Server.GetLastError();

            // Must Prevent Looping!
            if (!Request.PhysicalPath.ToLowerInvariant().Contains("error.aspx"))
                new Redirect("System/Error.aspx");
        }


        /// <summary> Handles the End event of the Session control.	
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void Session_End(object sender, EventArgs e)
        {
        }

        private void Application_End(Object sender, EventArgs e)
        {
            //  Code that runs on application shutdown
            TradingCenterHttpApplication.OnEnd();
        }
    }
}